package com.qingke.ocr.dao;

import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.qingke.ocr.pojo.User;

public class OCRDAO {
	
	
	private String resource = "mybatis_conf.xml";
	private InputStream is=null;
	private SqlSessionFactory sessionFactory = null;
	private SqlSession session = null;
	
	{
		is=OCRDAO.class.getClassLoader().getResourceAsStream(resource);
		sessionFactory = new SqlSessionFactoryBuilder().build(is);
		session = sessionFactory.openSession();
	}
    
	
    public boolean isUsernameExist(String username){
    	User user=new User();
    	user.setUsername(username);
    	UserMapper um=session.getMapper(UserMapper.class);
    	List<User> list=um.selectByUserName(user);
    	if(list.size()>0)
    		return true;
    	else
    		return false;
    }
    
    public User login(String username,String password){
    	User user=new User();
    	user.setUsername(username);
    	user.setPassword(password);
    	UserMapper um=session.getMapper(UserMapper.class);
    	List<User> list=um.selectByUsernameAndPassword(user);
    	if(list.size()>0)
    		return list.get(0);
    	else
    		return null;
    	
    }
    
    public boolean register(String username,String password,String nickname){
    	int count=0;
		UserMapper um=session.getMapper(UserMapper.class);
		User user=new User();
    	user.setUsername(username);
    	user.setPassword(password);
    	user.setNickname(nickname);
		try{
			count+=um.insert(user);
			session.commit();
		}catch(Exception e){
			e.printStackTrace();
			session.rollback();
		}
		if(count>0)
			return true;
		else
			return false;
    }
}
